/************************************************************
 * Project Name         [Thinking_In_Java]
 * File Name            [Example_04_IORedirection.java]
 * Creation Date        [09-Jul-2014]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ************************************************************/
package pkg_09_io.basic;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * IO重定向
 * 
 * @author 不落的太阳(Sean Yang)
 * @version 1.0
 * @since JDK 6
 * 
 */
public class Example_04_IORedirection {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		PrintStream ps_out = null;
		PrintStream ps_err = null;

		try {
			ps_out = new PrintStream(new FileOutputStream("io_out.txt", true));
			ps_err = new PrintStream(new FileOutputStream("io_err.txt", true));

			/*
			 * 设置输出和错误的重定向
			 */
			System.setOut(ps_out);
			System.setErr(ps_err);

			int count = 0; // 输入了几个数字
			int total = 0; // 表示总数
			int avg = 0; // 表示平均数
			int number = 0; // 表示每次输入的数字
			BufferedReader br = new BufferedReader(new InputStreamReader(
					System.in));
			String temp = br.readLine();
			while (temp != null && !temp.equalsIgnoreCase("over")) {
				number = Integer.parseInt(temp);
				count++;
				total += number;
				avg = total / count;
				System.out.println(new String(("输入了" + count + "个数字, 总和为: "
						+ total + "平均数为: " + avg).getBytes("UTF-8")));
				temp = br.readLine();
			}
			br.close();
		} catch (Exception e) {
			try {
				System.err.println(new String(("出错时间: " + new Date())
						.getBytes("UTF-8")));
				System.err.println(new String("出错信息为: ".getBytes("UTF-8")));
				e.printStackTrace(ps_err);
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}
		} finally {
			try {
				ps_out.close();
				ps_err.close();
			} catch (Exception e) {
				try {
					System.err.println(new String(("出错时间: " + new Date())
							.getBytes("UTF-8")));
					System.err.println(new String("出错信息为: ".getBytes("UTF-8")));
					e.printStackTrace(ps_err);
				} catch (UnsupportedEncodingException e1) {
					e1.printStackTrace();
				}
			}
		}
	}

}
